#include "deamon_runner.h"
#include "deamon_process.h"
#include <assert.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include "thirdparty/log.h"
#include <signal.h>

static SubProcess subprocess[1];
static int is_running = 1;

void deamon_runner_close(int sig)
{
    assert(sig == SIGTERM);
    is_running = 0;
}
int deamon_runner_run()
{
    if (daemon(0, 1) < 0) {
        log_error("deamon error");
        exit(EXIT_FAILURE);
    }

    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);
    open("/dev/null", O_RDWR);
    open(LOG_FILE, O_RDWR | O_CREAT, 0644);
    open(LOG_FILE, O_RDWR | O_CREAT, 0644);

    deamon_process_init(subprocess, "app");
    for (int i = 0; i < 1; i++)
    {
       deamon_process_start(subprocess); 
    }

    signal(SIGTERM, deamon_runner_close);
    while (is_running) {
        pid_t pid = waitpid(-1, NULL, WNOHANG);
        if(pid < 0)
        {
            log_warn("waitpid error");
            continue;
        }
        if (pid == 0)
        {
            usleep(100000);
            continue;
        }
        for (int i = 0; i < 1; i++)
        {
            if(pid == subprocess[i].pid)
            {
                log_warn("subprocess %s exit, restarting....", subprocess[i].name);
                deamon_process_start(subprocess + i);
            }
        }
    }
    for (int i = 0; i < 1; i ++) {
        deamon_process_stop(subprocess + i);
    }

    return 0;
}